-- Lua Battle System - 决策制定器

local Logger = require("utils.logger")
local TableUtils = require("utils.table_utils")

local DecisionMaker = {
    -- 决策类型
    decision_types = {
        SKILL = "skill",
        ITEM = "item",
        DEFEND = "defend",
        FLEE = "flee"
    },
    
    -- 决策评估权重
    evaluation_weights = {
        damage = 0.3,
        healing = 0.2,
        status_effects = 0.2,
        resource_cost = 0.15,
        risk = 0.15
    }
}

-- 决策构造函数
function DecisionMaker:new()
    local o = {}
    setmetatable(o, self)
    self.__index = self
    return o
end

-- 生成决策选项
function DecisionMaker:generate_decisions(character, battle_state)
    local decisions = {}
    
    -- 生成技能使用决策
    self:generate_skill_decisions(character, battle_state, decisions)
    
    -- 生成物品使用决策
    self:generate_item_decisions(character, battle_state, decisions)
    
    -- 生成防御决策
    self:generate_defend_decisions(character, battle_state, decisions)
    
    -- 生成逃跑决策
    self:generate_flee_decisions(character, battle_state, decisions)
    
    return decisions
end

-- 生成技能使用决策
function DecisionMaker:generate_skill_decisions(character, battle_state, decisions)
    -- 遍历所有可用技能
    for _, skill in ipairs(character.skills) do
        if skill:is_usable(character) then
            -- 为每个技能生成目标决策
            for _, target in ipairs(battle_state.characters) do
                -- 检查目标是否有效
                if self:is_valid_target(skill, character, target) then
                    table.insert(decisions, {
                        type = self.decision_types.SKILL,
                        skill = skill,
                        target = target,
                        priority = 0,
                        score = 0
                    })
                end
            end
        end
    end
end

-- 生成物品使用决策
function DecisionMaker:generate_item_decisions(character, battle_state, decisions)
    -- 遍历所有物品
    for item_id, quantity in pairs(character.items) do
        if quantity > 0 then
            -- 获取物品实例
            local ItemManager = require("items.item_manager")
            local item = ItemManager:get_item(item_id)
            if item and item:is_usable("battle") then
                -- 为每个物品生成目标决策
                for _, target in ipairs(battle_state.characters) do
                    -- 检查目标是否有效
                    if self:is_valid_item_target(item, character, target) then
                        table.insert(decisions, {
                            type = self.decision_types.ITEM,
                            item = item,
                            target = target,
                            priority = 0,
                            score = 0
                        })
                    end
                end
            end
        end
    end
end

-- 生成防御决策
function DecisionMaker:generate_defend_decisions(character, battle_state, decisions)
    table.insert(decisions, {
        type = self.decision_types.DEFEND,
        target = character,
        priority = 0,
        score = 0
    })
end

-- 生成逃跑决策
function DecisionMaker:generate_flee_decisions(character, battle_state, decisions)
    -- 检查是否允许逃跑
    local BattleConfig = require("config.battle_config")
    if BattleConfig.battle_rules.enable_flee then
        table.insert(decisions, {
            type = self.decision_types.FLEE,
            priority = 0,
            score = 0
        })
    end
end

-- 检查技能目标是否有效
function DecisionMaker:is_valid_target(skill, character, target)
    -- 检查目标是否存活
    if not target.is_alive then
        return false
    end
    
    -- 检查目标类型
    if skill.target_type == "enemy" and target.team_id == character.team_id then
        return false
    end
    
    if skill.target_type == "ally" and target.team_id ~= character.team_id then
        return false
    end
    
    if skill.target_type == "self" and target.id ~= character.id then
        return false
    end
    
    return true
end

-- 检查物品目标是否有效
function DecisionMaker:is_valid_item_target(item, character, target)
    -- 简化处理，实际应该根据物品类型和目标类型检查
    return target.is_alive
end

-- 评估决策选项
function DecisionMaker:evaluate_decisions(character, battle_state, decisions)
    local evaluated_decisions = {}
    
    for _, decision in ipairs(decisions) do
        local score = self:evaluate_decision(character, battle_state, decision)
        decision.score = score
        table.insert(evaluated_decisions, decision)
    end
    
    -- 按分数排序
    table.sort(evaluated_decisions, function(a, b) return a.score > b.score end)
    
    return evaluated_decisions
end

-- 评估单个决策
function DecisionMaker:evaluate_decision(character, battle_state, decision)
    local score = 0
    
    if decision.type == self.decision_types.SKILL then
        score = self:evaluate_skill_decision(character, battle_state, decision)
    elseif decision.type == self.decision_types.ITEM then
        score = self:evaluate_item_decision(character, battle_state, decision)
    elseif decision.type == self.decision_types.DEFEND then
        score = self:evaluate_defend_decision(character, battle_state, decision)
    elseif decision.type == self.decision_types.FLEE then
        score = self:evaluate_flee_decision(character, battle_state, decision)
    end
    
    return score
end

-- 评估技能决策
function DecisionMaker:evaluate_skill_decision(character, battle_state, decision)
    local score = 0
    local skill = decision.skill
    local target = decision.target
    
    -- 计算伤害评分
    if skill.damage.base > 0 then
        local damage_score = self:calculate_damage_score(character, skill, target)
        score = score + damage_score * self.evaluation_weights.damage
    end
    
    -- 计算治疗评分
    if skill.healing.base > 0 then
        local healing_score = self:calculate_healing_score(character, skill, target)
        score = score + healing_score * self.evaluation_weights.healing
    end
    
    -- 计算状态效果评分
    local status_score = self:calculate_status_effect_score(character, skill, target)
    score = score + status_score * self.evaluation_weights.status_effects
    
    -- 计算资源成本评分
    local resource_score = self:calculate_resource_cost_score(character, skill)
    score = score + resource_score * self.evaluation_weights.resource_cost
    
    -- 计算风险评分
    local risk_score = self:calculate_risk_score(character, skill, target)
    score = score + risk_score * self.evaluation_weights.risk
    
    return score
end

-- 评估物品决策
function DecisionMaker:evaluate_item_decision(character, battle_state, decision)
    local score = 0
    local item = decision.item
    local target = decision.target
    
    -- 简化处理，实际应该根据物品效果评估
    score = 50 -- 默认物品评分
    
    return score
end

-- 评估防御决策
function DecisionMaker:evaluate_defend_decision(character, battle_state, decision)
    local score = 0
    
    -- 根据角色生命值调整防御决策评分
    local health_percentage = character.hp / character.max_hp
    if health_percentage < 0.3 then
        score = 80 -- 生命值低时防御更有价值
    else
        score = 30 -- 生命值高时防御价值较低
    end
    
    return score
end

-- 评估逃跑决策
function DecisionMaker:evaluate_flee_decision(character, battle_state, decision)
    local score = 0
    
    -- 计算逃跑成功率
    local BattleConfig = require("config.battle_config")
    local flee_chance = BattleConfig.battle_rules.flee_success_rate
    
    -- 根据队伍生命值调整逃跑决策评分
    local team_health = 0
    local team_max_health = 0
    for _, ally in ipairs(battle_state.characters) do
        if ally.team_id == character.team_id then
            team_health = team_health + ally.hp
            team_max_health = team_max_health + ally.max_hp
        end
    end
    
    local team_health_percentage = team_health / team_max_health
    if team_health_percentage < 0.2 then
        score = flee_chance * 100 -- 队伍生命值低时逃跑更有价值
    else
        score = flee_chance * 20 -- 队伍生命值高时逃跑价值较低
    end
    
    return score
end

-- 计算伤害评分
function DecisionMaker:calculate_damage_score(character, skill, target)
    local damage = skill:calculate_damage(character, target)
    
    -- 考虑目标生命值
    local target_health_percentage = target.hp / target.max_hp
    if target_health_percentage < 0.2 then
        return damage * 1.5 -- 优先攻击低生命值目标
    end
    
    return damage
end

-- 计算治疗评分
function DecisionMaker:calculate_healing_score(character, skill, target)
    local healing = skill:calculate_healing(character, target)
    
    -- 考虑目标生命值
    local target_health_percentage = target.hp / target.max_hp
    if target_health_percentage < 0.3 then
        return healing * 2 -- 优先治疗低生命值目标
    end
    
    return healing
end

-- 计算状态效果评分
function DecisionMaker:calculate_status_effect_score(character, skill, target)
    local score = 0
    
    -- 计算目标状态效果价值
    for _, effect_info in ipairs(skill.status_effects.target) do
        score = score + self:get_status_effect_value(effect_info.id)
    end
    
    -- 计算施法者状态效果价值
    for _, effect_info in ipairs(skill.status_effects.caster) do
        score = score + self:get_status_effect_value(effect_info.id)
    end
    
    return score
end

-- 计算资源成本评分
function DecisionMaker:calculate_resource_cost_score(character, skill)
    local cost = skill.cost.mp
    local mp_percentage = character.mp / character.max_mp
    
    -- 资源成本评分（成本越低，评分越高）
    local score = 100 - (cost / character.max_mp) * 100
    
    -- MP不足时调整评分
    if mp_percentage < 0.2 then
        score = score * 2 -- MP不足时优先使用低消耗技能
    end
    
    return score
end

-- 计算风险评分
function DecisionMaker:calculate_risk_score(character, skill, target)
    local risk = 0
    
    -- 简化处理，实际应该根据技能效果和目标状态计算风险
    
    return 100 - risk -- 风险越低，评分越高
end

-- 获取状态效果价值
function DecisionMaker:get_status_effect_value(effect_id)
    local value_map = {
        burn = 20,
        freeze = 30,
        poison = 15,
        attack_buff = 25,
        defense_buff = 25,
        speed_buff = 20
    }
    
    return value_map[effect_id] or 10
end

-- 选择最佳决策
function DecisionMaker:select_best_decision(decisions)
    if TableUtils.is_empty(decisions) then
        Logger.warn("没有可用的决策选项")
        return nil
    end
    
    -- 返回评分最高的决策
    return decisions[1]
end

-- 执行决策
function DecisionMaker:execute_decision(character, decision)
    if not decision then
        Logger.error("决策为空，无法执行")
        return nil
    end
    
    local result = {}
    
    if decision.type == self.decision_types.SKILL then
        result = self:execute_skill_decision(character, decision)
    elseif decision.type == self.decision_types.ITEM then
        result = self:execute_item_decision(character, decision)
    elseif decision.type == self.decision_types.DEFEND then
        result = self:execute_defend_decision(character, decision)
    elseif decision.type == self.decision_types.FLEE then
        result = self:execute_flee_decision(character, decision)
    end
    
    return result
end

-- 执行技能决策
function DecisionMaker:execute_skill_decision(character, decision)
    local result = decision.skill:execute(character, decision.target)
    return result
end

-- 执行物品决策
function DecisionMaker:execute_item_decision(character, decision)
    local ItemManager = require("items.item_manager")
    local result = ItemManager:use_item(character, decision.item.id, decision.target)
    return result
end

-- 执行防御决策
function DecisionMaker:execute_defend_decision(character, decision)
    -- 防御效果：减少受到的伤害
    character.defense = character.defense * 1.5
    character.magic_defense = character.magic_defense * 1.5
    
    Logger.info(character.name .. " 进入防御状态，防御力提升50%")
    
    return {
        success = true,
        message = character.name .. " 进入防御状态"
    }
end

-- 执行逃跑决策
function DecisionMaker:execute_flee_decision(character, decision)
    local BattleConfig = require("config.battle_config")
    local flee_chance = BattleConfig.battle_rules.flee_success_rate
    
    if math.random() < flee_chance then
        Logger.info(character.name .. " 成功逃跑！")
        return {
            success = true,
            fled = true,
            message = character.name .. " 成功逃跑"
        }
    else
        Logger.info(character.name .. " 逃跑失败！")
        return {
            success = false,
            fled = false,
            message = character.name .. " 逃跑失败"
        }
    end
end

-- 导出模块
return DecisionMaker